package com.rongke.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.rongke.commons.JsonResp;
import com.rongke.enums.FlowTypeEnum;
import com.rongke.model.Account;
import com.rongke.model.FlowDetail;
import com.rongke.model.Muser;
import com.rongke.redis.CacheUtil;
import com.rongke.service.AccountService;
import com.rongke.service.FlowDetailService;
import com.rongke.service.MuserService;
import com.rongke.utils.PubLib;
import com.rongke.utils.QRCodeUtil2;
import com.rongke.utils.RequestUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.math.BigDecimal;
import java.util.*;

/**
 * @AccountController
 * @Controller
 * @version : Ver 1.0
 */
@RestController
@RequestMapping(value="/api/account")
@Transactional
@CrossOrigin
public class AccountController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private AccountService accountService;
    @Autowired
    private CacheUtil cacheUtil;
    @Autowired
    private FlowDetailService flowDetailService;
    @Autowired
    private MuserService muserService;
    /**
     * @添加
     * @param account
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/add", method = RequestMethod.POST)
    public JsonResp addAccount(@RequestBody Account account){
        log.debug("添加");
        accountService.insert(account);
        return JsonResp.ok(account);
    }

    /**
     * @修改
     * @param account
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/update", method = RequestMethod.POST)
    public JsonResp updateAccount(@RequestBody Account account){
        log.debug("修改");
        accountService.updateById(account);
        return JsonResp.ok(account);
    }
    /**
     * @获取账户余额列表
     * @param name  查询条件姓名或电话
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/findAccountList", method = RequestMethod.GET)
    public JsonResp findAccountList(Page page,String name){
        log.debug("获取账户余额列表");
        Map map=new HashMap();
        map.put("startIndex",(page.getCurrent()-1)*page.getCurrent());
        map.put("size",page.getSize());
        if (name != null && !"".equals(name.trim())) {
            //为数字则查询电话号码，否则查询姓名
            if(name.matches("^[0-9]*$")){
                map.put("phone", name);
            }else{
                map.put("userName", name);
            }
        }
        List<Account> accountList=accountService.selectAllAccountAndUser(map);
        Integer size=accountService.selectAccountAndUserNums(map);
        page.setRecords(accountList);
        page.setTotal(size);
        return JsonResp.ok(page);
    }


    /**
     * @雅币转让
     * @param phone  接受人电话
     *         num  转账雅币数量
     *          nickName  接受人昵称
     *          token  令牌
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/yaBiTransfer", method = RequestMethod.GET)
    public JsonResp duobiTransfer(String phone,Integer num,String nickName,String token){
        log.debug("雅币转让");
        if(!cacheUtil.hasKey(token)){
            return JsonResp.fa(muserService.LOGINSTR);
        }
        Long userId=Long.valueOf(cacheUtil.get(token));
        EntityWrapper<Account> ew=new EntityWrapper<>();
        ew.eq("muser_id",userId);
        //转账人账户
        Account request=accountService.selectOne(ew);
        EntityWrapper<Muser> ewResponce=new EntityWrapper<>();
        ewResponce.eq("phone",phone);
        Muser responseUser=muserService.selectOne(ewResponce);
        if(!responseUser.getUserName().equals(nickName)){
            return JsonResp.fa("账号和用户人不匹配");
        }
        if(request.getYaBi().compareTo(new BigDecimal(num))<0){
            return JsonResp.fa("账户余额不足");
        }else {
            request.setYaBi(request.getYaBi().subtract(new BigDecimal(num)));
            accountService.updateById(request);
        }
        EntityWrapper<Account> ewResAcc=new EntityWrapper<>();
        ewResAcc.eq("muser_id",responseUser.getId());
        //接受人账户
        Account response=accountService.selectOne(ewResAcc);
        response.setYaBi(response.getYaBi().add(new BigDecimal(num)));
        accountService.updateById(response);
        //****************流水记录*******************//
        FlowDetail turnOut=new FlowDetail();
        turnOut.setMuserId(userId);
        turnOut.setMoney(new BigDecimal(num).multiply(new BigDecimal("-1")));
        turnOut.setFlowType(FlowTypeEnum.TRANSFER.getType());
        turnOut.setTransferInMuser(responseUser.getId());
        turnOut.setTransferOutMuser(userId);
        turnOut.setGmtDatetime(new Date());
        turnOut.setTitle("雅币转出金额"+num);
        flowDetailService.insert(turnOut);

        FlowDetail turnIn=new FlowDetail();
        turnIn.setTransferInMuser(responseUser.getId());
        turnOut.setFlowType(FlowTypeEnum.TRANSFER.getType());
        turnIn.setTransferOutMuser(userId);
        turnIn.setTitle("雅币转入金额"+num);
        turnIn.setMoney(new BigDecimal(num));
        turnIn.setGmtDatetime(new Date());
        turnIn.setMuserId(responseUser.getId());
        flowDetailService.insert(turnIn);
        return JsonResp.ok();
    }


    /**
     * @根据id查找
     * @param id
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/selectOne", method = RequestMethod.GET)
    public JsonResp selectAccount(Long id){
        log.debug("查找");
        Account account = accountService.selectById(id);
        return JsonResp.ok(account);
    }

    /**
     * @根据id查找
     * @param token  用户令牌
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/findUserBalance", method = RequestMethod.GET)
    public JsonResp findUserBalance(String token){
        log.debug("查找");
        if(!cacheUtil.hasKey(token)){
            return JsonResp.fa(muserService.LOGINSTR);
        }
        Long userId=Long.valueOf(cacheUtil.get(token));
        Account account = accountService.selectAccountByUserId(userId);
        return JsonResp.ok(account);
    }


    @RequestMapping(value = "/uptMemberQRCode",method = RequestMethod.GET)
    public JsonResp uptMemberQRCode(Long id,HttpServletRequest request){
        String link = "https://wx.miduu.com/1.6.0zhuce_tiyan.html?id=" + id;
        String url = RequestUtils.getHostPath(request);
        String path = PubLib.getFileDir(request);
        path+= File.separator + UUID.randomUUID() + ".png";
        File saveFile = new File(path);
        String logoPath = PubLib.getFileDir(request) + File.separator + "android-template.png";
        try {
            QRCodeUtil2.encode(link, 600, 600, logoPath, path);
        } catch (Exception e) {
            return JsonResp.fa("个人二维码生成失败");
        }
        String qrCode = url + "/" + saveFile.getParentFile().getName() + "/" + saveFile.getName();
        return JsonResp.ok(qrCode);
    }








}
